package com.fBlog.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.fBlog.dao.impl.UserDaoI;
import com.fBlog.pojo.Alphoto;
import com.fBlog.pojo.Speak;
import com.fBlog.service.impl.PhotoServiceI;
import com.fBlog.service.impl.SpeakServiceI;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.fBlog.pojo.Tuser;
import com.fBlog.pojo.User;
import com.fBlog.service.impl.UserServiceI;


@Controller
@RequestMapping("/userController")
public class UserController {

    @Autowired
    private UserServiceI userService;
    @Autowired
    private PhotoServiceI photoService;
    @Autowired
    private SpeakServiceI speakService;
    @Autowired
    private UserDaoI userDao;

    @RequestMapping("/login")
    public void login(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "familyName") String familyName, @RequestParam(value = "userName") String name, @RequestParam(value = "password") String pwd) {
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpSession session = request.getSession();
        User user = userService.login(familyName, name, pwd);
        if (user != null) {
            session.setAttribute("user", user);
            writer.print("0");
        } else {
            writer.print("1");
        }
    }

    @RequestMapping("/quit")
    public void quit(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        session.removeAttribute("user");
    }

    @RequestMapping("/reg")
    public void reg(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "familyName") String familyName, @RequestParam(value = "admin") String admin, @RequestParam(value = "password1") String password) {
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpSession session = request.getSession();
        //注册家庭信息
        String code = userService.regFamily(familyName, admin, password);
        writer.print(code);
    }
    @RequestMapping("/saveUser")
    public void saveUser(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "userName") String userName, @RequestParam(value = "role") String role, @RequestParam(value = "password2") String password) {
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpSession session = request.getSession();
        User user =(User) session.getAttribute("user");
        String familyId = user.getFamilyId();
        //注册家庭信息
        String code = userService.saveUser(familyId,userName, role, password);
        writer.print(code);
    }
    @RequestMapping("/updateUser")
    public void updateUser(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "userId") String userId, @RequestParam(value = "userName") String userName, @RequestParam(value = "role") String role, @RequestParam(value = "password2") String password) {
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpSession session = request.getSession();
        User user =(User) session.getAttribute("user");
        String familyId = user.getFamilyId();
        //注册家庭信息
        String code = userService.updateUser(userId,familyId,userName, role, password);
        writer.print(code);
    }

    @RequestMapping("/deleteUser")
    public void deleteUser(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "userId") String userId){
        String code = "0";
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Tuser u = userDao.get(Tuser.class,userId);
        User user = new User();
        BeanUtils.copyProperties(u,user);
        user.setFamilyCreateTime(u.getFamily().getCreateTime());
        user.setFamilyId(u.getFamily().getId());
        user.setFamilyName(u.getFamily().getName());
        String path = request.getServletContext().getRealPath(File.separator+"images"+File.separator+"albums")+File.separator;
        //删除该用户的所有相册和照片
        //获取该用户所有相册
        List<Alphoto> list = photoService.get(user.getId());
        if(list!=null && list.size()>0){
            for(Alphoto a : list){
                String code1 = photoService.deleteAlphoto(a.getId(),user,path);
                if(!code1.equals("0")){
                    //标记1标识删除该用户相册时出错。
                    code = "1";
                    break;
                }
            }
        }
        //删除该用户的所有动态
        //获取该用户所有动态
        List<Speak> l = speakService.getThisUserSpeak(user.getFamilyId(),userId);
        if(l!=null && l.size()>0){
            for(Speak s : l){
                Boolean b = speakService.deleteSpeak(s.getId());
                if(!b){
                    //标记2标识删除该用户动态时出错。
                    code = "2";
                    break;
                }
            }
        }
        //删除该用户的所有涉及的评论或回复（comment）暂时没有涉及的外键，不需要删除

        if(code.equals("0")){
            userDao.executeSql("delete from tuser where id = '"+userId+"'");
        }
        writer.print(code);
    }
}
